const Food = require("../../mongoose/models/foods");
const Cate = require("../../mongoose/models/Cate");
const User = require("../../mongoose/models/users");
const Order = require("../../mongoose/models/order");
const Counters = require("../../mongoose/models/counters");

const foodFind = (callback, data) => {
  const queryObj = { id: 1, name: 1, price: 1, img: 1, _id: 0, catid: 1 };
  if (!data || JSON.stringify(data) == "{}") {
    // 搜索全部
    Food.find({}, queryObj, function (err, foods) {
      if (err) {
        callback(err);
      }
      callback(foods);
    });
  } else {
    Food.find(data, queryObj, function (err, foods) {
      if (err) {
        callback(err);
      }
      callback(foods);
    });
  }
};

/**
 * callback 是获得分类之后的回调
 * data 是传递的参数 也就是查询的条件
 */
const cateFind = (callback, data) => {
  console.log(data, "data");
  Cate.find(
    data,
    { catid: 1, name: 1, remark: 1, _id: 0, sort: 1, store: 1 },
    function (err, cates) {
      if (err) {
        callback(err);
      }
      callback(cates);
    }
  );
};

const userFind = (callback, data) => {
  const queryObj = {};
  if (!data || JSON.stringify(data) == "{}") {
    // 搜索全部
    User.find({}, queryObj, function (err, users) {
      if (err) {
        callback(err);
      }
      callback(users);
    });
  } else {
    User.find(data, queryObj, function (err, users) {
      if (err) {
        callback(err);
      }
      callback(users);
    });
  }
};

const orderFind = (callback, data) => {
  console.log(data, "data");
  Order.find(data, null, function (err, orders) {
    if (err) {
      callback(err);
    }
    callback(orders);
  }).sort({ created_time: -1 });
};

function getNextSequenceValue(sequenceName) {
  return new Promise((resolve, reject) => {
    Counters.findOneAndUpdate(
      { _id: sequenceName },
      { $inc: { sequence_value: 1 } },
      (err, data) => {
        if (err) {
          reject(err);
        }
        resolve(data.sequence_value);
      }
    );
  });
}

module.exports = {
  foodFind,
  cateFind,
  getNextSequenceValue,
  userFind,
  orderFind,
};
